﻿using Batman.Core;
using IdentityServer4;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Entities;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Web.Api.Controllers
{
    [Authorize(IdentityServerConstants.LocalApi.PolicyName)]
    [ApiController]
    [Route("api/[controller]")]
    public class ClientsController : ControllerBase
    {
        IServiceScopeFactory ServiceScopeFactory;

        IClientStore ClientStore;

        public ClientsController(IServiceScopeFactory serviceScopeFactory, IClientStore clientStore)
        {
            ServiceScopeFactory = serviceScopeFactory;
            ClientStore = clientStore;
        }

        public async Task<PagedResponse> Get()
        {
            using (var serviceScope = ServiceScopeFactory.CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
                var clients = context.Clients.Include(c => c.AllowedGrantTypes)
                    .Include(t => t.AllowedScopes)
                    .AsNoTracking().ToList();

                clients.ForEach(t => t.AllowedGrantTypes.ForEach(a => a.Client = null));
                clients.ForEach(t => t.AllowedScopes.ForEach(a => a.Client = null));


                return PagedResponse.New(0, clients);
            }
        }

        [HttpPost]
        public async Task<ResponseBase> Post([FromForm]List<IdentityServer4.Models.Client> clients)
        {
            if (clients == null) return new ResponseBase(false, "空数据");

            // 加密secret
            clients.ForEach(c => c.ClientSecrets.ToList().ForEach(cs => cs.Value = cs.Value.Sha256()));

            using (var serviceScope = ServiceScopeFactory.CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
                var clientEntities = clients.Select(c => c.ToEntity()).ToList();
                await context.Clients.AddRangeAsync(clientEntities);

                await context.SaveChangesAsync();
                return new ResponseBase(clientEntities);
            }
        }


        [HttpDelete]
        public async Task<ResponseBase> Delete([FromForm]List<int> ids)
        {
            if (ids == null || ids.Count == 0) return new ResponseBase(false, "空数据");

            using (var serviceScope = ServiceScopeFactory.CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();

                var clients = context.Clients.AsNoTracking().Where(t => ids.Contains(t.Id)).ToList();

                clients.ForEach(t => context.Entry(t).State = EntityState.Deleted);

                await context.SaveChangesAsync();
                return new ResponseBase();
            }
        }

        [HttpPut]
        [Route("Scopes")]
        public ResponseBase UpdateScopes(int id, [FromForm]List<string> scopeNames)
        {
            using (var serviceScope = ServiceScopeFactory.CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
                var client = context.Clients.AsNoTracking().Include(t => t.AllowedScopes)
                    .FirstOrDefault(t => t.Id == id);

                if (client == null) return new ResponseBase(false, "客户端不存在");

                //- 新增
                foreach (var scopeName in scopeNames)
                {
                    var isOld = client.AllowedScopes.Any(s => s.Scope == scopeName);

                    if (isOld) continue;
                    client.AllowedScopes.Add(new ClientScope { Scope = scopeName, ClientId = client.Id });
                }

                //- 删除
                var removingItems = client.AllowedScopes.Where(t => scopeNames.All(s => s != t.Scope)).ToList();

                removingItems.ForEach(t => context.Entry(t).State = EntityState.Deleted);
                context.Clients.Update(client);
                context.SaveChanges();
                client.AllowedScopes.ForEach(t => t.Client = null);
                return new ResponseBase(client);
            }
        }
    }
}
